<?php

declare(strict_types=1);

/**
 * CSV FILE EXPORT
 */
namespace App\Service\Export;

use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Response;

/**
 * csv导出
 * Class CSV
 * @package App\Service
 */
class CsvExport
{
    const CONTENT_TYPE = 'text/csv';
    static function export(array $head,array $body,string $file_name)
    {
        $head_keys = array_keys($head);
        $head_values = array_values($head);
        $fileData = self::utfToGbk(implode(',',$head_values)) . "\n";

        if(strpos($file_name,'.') === false){
            $file_name .= '.csv';
        }
        
        foreach ($body as $value) {
            $temp_arr = [];
            foreach($head_keys as $key){
                $temp_arr[] = $value[$key] ?? '';
            }
            $fileData .= self::utfToGbk(implode(',',$temp_arr)) . "\n";
        }
        
        $response = new Response();
        return $response->withHeader('content-description', 'File Transfer')
        ->withHeader('Content-Type',"text/csv;charset=utf-8")
        ->withHeader('Content-Disposition', "attachment; filename={$file_name}")
        ->withHeader('Content-Transfer-Encoding', 'binary')
        ->withHeader('pragma', 'public')
        ->withBody(new SwooleStream($fileData));
    }

    /**
     * 字符转换（utf-8 => GBK）
     * @param $data
     * @return false|string
     */
    static function utfToGbk($data)
    {
        return $data;
        return iconv("GBK", "UTF-8", $data);
    }

}